# -*- coding:utf-8 -*-
from flask_login import login_required, logout_user, current_user, login_user
from flask import render_template, jsonify, request, redirect
from ..utils import check_user, create_user
from .. import login_manager
from ..models import User
from .. import app

import json


@login_manager.user_loader
def get_user(userid):
    return User.objects(id=userid).first()


@app.route('/')
def index():
    '''
    主页/登录页
    '''
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    '''
    登录：POST
    登录页:GET
    '''
    if request.method == 'POST':
        err_pack = {'Result': 'ERR'}
        try:
            param = json.loads(request.data.decode('utf-8'))
        except ValueError:
            err_pack['Reason'] = 'NO JSON'
            return jsonify(err_pack)
        email = param.get('email', '')
        password =  param.get('password', '')
        if not email:
            err_pack['Reason'] = 'Miss Email'
            return jsonify(err_pack)
        if not password:
            err_pack['Reason'] = 'Miss Password'
            return jsonify(err_pack)
        user = User.objects(email=email).first()
        if not user:
            err_pack['Reason'] = 'Not user'
            return jsonify(err_pack)
        if not user.verify_password(password):
            err_pack['Reason'] = 'Password error'
            return jsonify(err_pack)
        login_user(user)
        if user.identity == 'admin': # 管理员后台
            next_url = '/admin'
        elif user.identity == 'senior': # 高级用户界面
            next_url = '/consumer'
        elif user.identity == 'ordinary': # 普通用户界面
            next_url = '/consumer'
        else:
            next_url = '/'
        return jsonify({
                'Result': 'OK',
                'Username': user.nickname,
                'next_url': next_url
            })
    return render_template('index.html')


@app.route('/logout')
@login_required
def logout():
    '''
    登出
    '''
    logout_user()
    return redirect('/')


@app.route('/register', methods=['GET', 'POST'])
def register():
    '''
    用户注册
    '''
    if request.method == 'POST':
        err_pack = {'Result': 'ERR'}
        try:
            param = json.loads(request.data.decode('utf-8'))
        except ValueError:
            err_pack['Reason'] = 'NO JSON'
            return jsonify(err_pack)
        nickname = param.get('nickname', '')
        email = param.get('email', '')
        password = param.get('password', '')
        if not nickname:
            err_pack['Reason'] = 'Miss Nickname'
            return jsonify(err_pack)
        if not email:
            err_pack['Reason'] = 'Miss Email'
            return jsonify(err_pack)
        if not password:
            err_pack['Reason'] = 'Miss Password'
            return jsonify(err_pack)
        if check_user(email):
            err_pack['Reason'] = 'User Exist'
            return jsonify(err_pack)
        new_user = create_user(email,nickname, password)
        if new_user:
            return jsonify({
                    'Result': 'OK',
                    'New_user': new_user.nickname,
                    'next_url': '/consumer'
                })
    return render_template('register.html')



        

